package ve.usb.coord.colision;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import ve.usb.cohesion.runtime.CohesionAction;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import ve.usb.coord.colision.hibernate.*;

import org.apache.struts.upload.FormFile;


/**
 * Manejo de elementos de la entidad Asignatura.<br>
 */
public class AccionesAsignatura extends CohesionAction {
    
/**
     * Acción llamada por Struts para ejecutar la acción AsignaturaDepartamentoCrearI.
     * Prepara la vista de captura de datos de una entidad para realizar una inserción.<br>
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward AsignaturaDepartamentoCrearI(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        //Salidas
        final String SALIDA_0 = "asignaturaDepartamentoCrear";

        String salida = SALIDA_0;        
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {

            HttpSession sess = request.getSession();
            FAsignatura fFAsignatura = (FAsignatura)sess.getAttribute("FAsignatura");
            if (fFAsignatura==null) {
                fFAsignatura = new FAsignatura();
                sess.setAttribute("FAsignatura", fFAsignatura);
            } else {
                fFAsignatura.reset(mapping, request);
            }
             
            //Feed for combo listDepartamento.
            {java.util.List<ve.usb.cohesion.runtime.Pair> list = 
               (java.util.List<ve.usb.cohesion.runtime.Pair>)s.createQuery(
               "select new ve.usb.cohesion.runtime.Pair(nombre, idDepartamento) " + 
               "from Departamento").list();
             list.add(0,new ve.usb.cohesion.runtime.Pair("Ninguna", 0));
             fFAsignatura.setListDepartamento(list);
            }

            fFAsignatura.setDepartamento(Long.parseLong((String)request.getParameter("idDepartamento")));

            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        }
        return mapping.findForward(salida);
    }

/**
     * Acción llamada por Struts para ejecutar la acción AsignaturaI.
     * Prepara la vista de actualización de una entidad.<br>
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward AsignaturaI(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        //Salidas
        final String SALIDA_0 = "asignatura";

        String salida = SALIDA_0;        
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {

            String id = request.getParameter("idAsignatura");
            Long idAsignatura = (id==null) ? 
                (Long)request.getSession().getAttribute("idAsignatura") :
                new Long(id);
            
            HttpSession sess = request.getSession();
            FAsignatura fFAsignatura = (FAsignatura)sess.getAttribute("FAsignatura");
            if (fFAsignatura==null) {
                fFAsignatura = new FAsignatura();
                sess.setAttribute("FAsignatura", fFAsignatura);
            } else {
                fFAsignatura.reset(mapping, request);
            }
            Asignatura asignatura = (Asignatura)s.load(Asignatura.class, idAsignatura);
            fFAsignatura.setIdAsignatura(asignatura.getIdAsignatura());

            fFAsignatura.setDepartamento(asignatura.getDepartamento().getIdDepartamento());

            fFAsignatura.setCodigo(asignatura.getCodigo());
            fFAsignatura.setNombre(asignatura.getNombre());
            fFAsignatura.setHorast(asignatura.getHorast());
            fFAsignatura.setHorasp(asignatura.getHorasp());
            fFAsignatura.setHorasl(asignatura.getHorasl());
            fFAsignatura.setPrograma1(null);

            //Feed for combo listDepartamento.
            {java.util.List<ve.usb.cohesion.runtime.Pair> list = 
               (java.util.List<ve.usb.cohesion.runtime.Pair>)s.createQuery(
               "select new ve.usb.cohesion.runtime.Pair(nombre, idDepartamento) " + 
               "from Departamento").list();
             list.add(0,new ve.usb.cohesion.runtime.Pair("Ninguna", 0));
             fFAsignatura.setListDepartamento(list);
            }


            request.getSession().setAttribute("idDepartamento", fFAsignatura.getDepartamento());

            request.getSession().setAttribute("idAsignatura", idAsignatura);

            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        }
        return mapping.findForward(salida);
    }

/**
     * Acción llamada por Struts para ejecutar la acción AsignaturaAct.
     * Registro de actualizaciones de una entidad.<br>
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward AsignaturaAct(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        //Salidas
        final String SALIDA_0 = "asignatura";

        String salida = SALIDA_0;        
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            FAsignatura fFAsignatura = (FAsignatura)form;

            FormFile myFile = fFAsignatura.getPrograma1();
            String nombrefile = new String();
            
            if(myFile == null){
                nombrefile = fFAsignatura.getPrograma2();
            }
            
            else{
            String contentType = myFile.getContentType();
            
            String fileName    = myFile.getFileName();
            //int fileSize       = myFile.getFileSize();
            byte[] fileData    = myFile.getFileData();
            //Get the servers upload directory real path name
            String filePath = getServlet().getServletContext().getRealPath("/") +"upload";
            /* Save file on the server */
            if(!fileName.equals("")){  
                    System.out.println("Server path:" +filePath);
                    //Create file
                    File fileToCreate = new File(filePath, fileName);
                    //If file does not exists create file                      
                    if(!fileToCreate.exists()){
                        FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
                        fileOutStream.write(myFile.getFileData());
                        fileOutStream.flush();
                        fileOutStream.close();
                        }     


                    }
            
            nombrefile = "http://localhost:8084/colisiones/upload/" + fileName;
            }
            
            
            Asignatura asignatura = (Asignatura)s.load(Asignatura.class, new Long(fFAsignatura.getIdAsignatura()));
            asignatura.setCodigo(fFAsignatura.getCodigo());
            asignatura.setNombre(fFAsignatura.getNombre());
            asignatura.setHorast(fFAsignatura.getHorast());
            asignatura.setHorasp(fFAsignatura.getHorasp());
            asignatura.setHorasl(fFAsignatura.getHorasl());
            asignatura.setPrograma(nombrefile);


            //Feed for combo listDepartamento.
            {java.util.List<ve.usb.cohesion.runtime.Pair> list = 
               (java.util.List<ve.usb.cohesion.runtime.Pair>)s.createQuery(
               "select new ve.usb.cohesion.runtime.Pair(nombre, idDepartamento) " + 
               "from Departamento").list();
             list.add(0,new ve.usb.cohesion.runtime.Pair("Ninguna", 0));
             fFAsignatura.setListDepartamento(list);
            }


            request.getSession().setAttribute("idDepartamento", fFAsignatura.getDepartamento());

            request.getSession().setAttribute("idAsignatura", asignatura.getIdAsignatura());

            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        }
        return mapping.findForward(salida);
    }

/**
     * Acción llamada por Struts para ejecutar la acción AsignaturaElim.
     * Elimina la entidad seleccionada.<br>
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward AsignaturaElim(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        //Salidas
        final String SALIDA_0 = "DepartamentoI";
        final String SALIDA_1 = "asignatura";

        String salida = SALIDA_0;        
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {

            String id = request.getParameter("idAsignatura");
            Long idAsignatura = (id==null) ? 
                (Long)request.getSession().getAttribute("idAsignatura") :
                new Long(id);
            Asignatura asignatura = (Asignatura)s.load(Asignatura.class, idAsignatura);

            long idDepartamento = asignatura.getDepartamento().getIdDepartamento();
            asignatura.getDepartamento().removeFromAsignaturas(asignatura);

            try {
                s.flush();
                request.getSession().setAttribute("idAsignatura", idAsignatura);

                request.getSession().setAttribute("idDepartamento", idDepartamento);

            } catch (Exception ex1) {
                ex1.printStackTrace();
                salida = SALIDA_1;
                request.setAttribute("msg", "No se pudo eliminar entidad.");
            }

            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        }
        return mapping.findForward(salida);
    }

/**
     * Acción llamada por Struts para ejecutar la acción AsignaturaCrear.
     * Registro de la creación de una asignatura.<br>
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions. 
     * These exceptios will normally be treated with 
     * the default exception action.
     */
    public ActionForward AsignaturaCrear(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        //Salidas
        final String SALIDA_1 = "DepartamentoI";

        String salida = SALIDA_1;        
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tr = s.beginTransaction();
        try {
            FAsignatura fFAsignatura = (FAsignatura)form;

            
            //String url = fFAsignatura.getPrograma2();
            String nombrefile = new String();
            
            //if( url != "" ){
                
                
                //nombrefile = url;
                
           //}
           
            //else{
               FormFile myFile = fFAsignatura.getPrograma1();
               String contentType = myFile.getContentType();
      
            if(contentType.equals("application/octet-stream") ){
                   nombrefile = "http://" + fFAsignatura.getPrograma2();
            }
               
            else{
                   
               String fileName    = myFile.getFileName();
               int fileSize       = myFile.getFileSize();
               byte[] fileData    = myFile.getFileData();
            //Get the servers upload directory real path name
            String filePath = getServlet().getServletContext().getRealPath("/") +"upload";
            /* Save file on the server */
            if(!fileName.equals("")){  
                   // System.out.println("Server path:" +filePath);
                    //Create file
                   File fileToCreate = new File(filePath, fileName);
                    //If file does not exists create file                      
                    if(!fileToCreate.exists()){
                          FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
                          fileOutStream.write(myFile.getFileData());
                          fileOutStream.flush();
                          fileOutStream.close();
                         }     


                    }
             nombrefile = "http://localhost:8084/colisiones/upload/" + fileName;
               //nombrefile = "http://localhost:8084/colisiones/upload/"  ; 
            }
            
            //}
            
            
            Asignatura asignatura = new Asignatura();
            asignatura.setCodigo(fFAsignatura.getCodigo());
            asignatura.setNombre(fFAsignatura.getNombre());
            asignatura.setHorast(fFAsignatura.getHorast());
            asignatura.setHorasp(fFAsignatura.getHorasp());
            asignatura.setHorasl(fFAsignatura.getHorasl());
            asignatura.setPrograma(nombrefile);


            {Departamento obj = (Departamento)s.load(Departamento.class, new Long(fFAsignatura.getDepartamento()));
             obj.addToAsignaturas(asignatura);
            }

            s.flush();
            fFAsignatura.setIdAsignatura(asignatura.getIdAsignatura());
            //Feed for combo listDepartamento.
            {java.util.List<ve.usb.cohesion.runtime.Pair> list = 
               (java.util.List<ve.usb.cohesion.runtime.Pair>)s.createQuery(
               "select new ve.usb.cohesion.runtime.Pair(nombre, idDepartamento) " + 
               "from Departamento").list();
             list.add(0,new ve.usb.cohesion.runtime.Pair("Ninguna", 0));
             fFAsignatura.setListDepartamento(list);
            }


            //fFAsignatura.setDepartamento(asignatura.getDepartamento().getIdDepartamento());
            request.getSession().setAttribute("idDepartamento", fFAsignatura.getDepartamento());

            request.getSession().setAttribute("idAsignatura", asignatura.getIdAsignatura());

            tr.commit();

        } catch (Exception ex) {
            tr.rollback();
            throw ex;
        }
        return mapping.findForward(salida);
    }



}